import { reactive, ref } from 'vue'

interface PagedData {
  data: any[]
  total: number
}

interface PageParams {
  page: number
  pageSize: number
}

export type FetchApi = (
  pageParams: PageParams,
  searchParams: Record<string, any>
) => Promise<PagedData>

export default function useTableData(fetchApi: FetchApi) {
  const dataLoading = ref(false)
  const tableData = ref<any[]>([])
  const pageParams: PageParams = reactive({
    page: 1,
    pageSize: 10
  })
  const total = ref(0)
  const handlePageChange = (page: number, pageSzie: number) => {
    pageParams.page = page
    pageParams.pageSize = pageSzie
    updateData()
  }

  const searchParams = ref<Record<string, any>>({})
  const searchData = () => {
    pageParams.page = 1
    updateData()
  }
  const resetData = () => {
    searchParams.value = {}
  }

  const updateData = async () => {
    dataLoading.value = true
    const response = await fetchApi(pageParams, searchParams.value)
    tableData.value = response.data
    total.value = response.total
    dataLoading.value = false
    // console.log(tableData.value)
  }

  return {
    dataLoading,
    tableData,
    pageParams,
    total,
    searchParams,
    updateData,
    searchData,
    resetData,
    handlePageChange
  }
}
